import React from 'react';

type ErrorBoundaryProps = {
  children: React.ReactNode;
  message?: string; // 新增的message属性
};

type ErrorBoundaryState = {
  hasError: boolean;
};

class ErrorBoundary extends React.Component<
  ErrorBoundaryProps,
  ErrorBoundaryState
> {
  state: ErrorBoundaryState = { hasError: false };

  static getDerivedStateFromError(_: Error): ErrorBoundaryState {
    return { hasError: true };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error('Error caught by ErrorBoundary:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div>
          <h1>{this.props.message || 'Something went wrong.'}</h1>
          {/* 优先使用外部传入的message，否则显示默认文本 */}
        </div>
      );
    }
    return this.props.children;
  }
}

export default ErrorBoundary;
